package com.enjoyor.emchatdemo;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.EditText;

import com.hyphenate.EMContactListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.exceptions.HyphenateException;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/9/6.
 */
public class MessageActivity extends AppCompatActivity {

    @Bind(R.id.et_info)
    EditText et_info;
    @Bind(R.id.et_toname)
    EditText et_toname;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);
        ButterKnife.bind(this);

        /*接收消息监听*/
        EMClient.getInstance().chatManager().addMessageListener(msgListener);
        /*添加好友监听*/
        EMClient.getInstance().contactManager().setContactListener(emContactListener);
    }

    @OnClick(R.id.bt_add)
    public void addUser() {
        //参数为要添加的好友的username和添加理由
        try {
            EMClient.getInstance().contactManager().addContact(et_toname.getText().toString(), et_info.getText().toString());
            Log.i("EM", "EM---MessageActivity------>添加好友");

        } catch (HyphenateException e) {
            e.printStackTrace();
        }
    }


    @OnClick(R.id.bt_sendtext)
    public void infoSendTxt() {
        //创建一条文本消息，content为消息文字内容，toChatUsername为对方用户或者群聊的id，后文皆是如此
        EMMessage message = EMMessage.createTxtSendMessage(et_info.getText().toString(), et_toname.getText().toString());
        //如果是群聊，设置chattype，默认是单聊
//        if (chatType == CHATTYPE_GROUP)
//            message.setChatType(EMMessage.ChatType.GroupChat);
        //发送消息
        EMClient.getInstance().chatManager().sendMessage(message);
    }

    @OnClick(R.id.bt_sendpic)
    public void InfoSendPic() {
        //imagePath为图片本地路径，false为不发送原图（默认超过100k的图片会压缩后发给对方），需要发送原图传true
        String imagePath = "";
        EMMessage message = EMMessage.createImageSendMessage(imagePath, false, et_toname.getText().toString());
        //如果是群聊，设置chattype，默认是单聊
//        if (chatType == CHATTYPE_GROUP)
//            message.setChatType(ChatType.GroupChat);
        EMClient.getInstance().chatManager().sendMessage(message);
    }


    private void refreshUIWithMessage(final List<EMMessage> messages) {
        runOnUiThread(new Runnable() {
            public void run() {
                et_info.setText(messages.toString());
            }
        });
    }

    private void agreeAddUser(final String user, final String reason) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new AlertDialog.Builder(MessageActivity.this)
                        .setTitle(user)
                        .setMessage(reason)
                        .setPositiveButton("AGREE", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                try {
                                    EMClient.getInstance().contactManager().acceptInvitation(user);
                                } catch (HyphenateException e) {
                                    e.printStackTrace();
                                }
                            }
                        })
                        .setNegativeButton("DISAGREE", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                try {
                                    EMClient.getInstance().contactManager().declineInvitation(user);
                                } catch (HyphenateException e) {
                                    e.printStackTrace();
                                }
                            }
                        })
                        .show();
            }
        });

    }


    EMMessageListener msgListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {

            Log.i("EM", "EM---MessageActivity------>收到消息");
            Log.i("EM", "EM---MessageActivity------>messages" + messages.toString());
            refreshUIWithMessage(messages);
            //收到消息
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            //收到透传消息
        }

        @Override
        public void onMessageReadAckReceived(List<EMMessage> messages) {
            //收到已读回执
        }

        @Override
        public void onMessageDeliveryAckReceived(List<EMMessage> message) {
            //收到已送达回执
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
            //消息状态变动
        }
    };
    EMContactListener emContactListener = new EMContactListener() {

        @Override
        public void onContactAgreed(String username) {
            //好友请求被同意
            Log.i("EM", "EM---MessageActivity------>好友请求被同意");
        }

        @Override
        public void onContactRefused(String username) {
            //好友请求被拒绝
            Log.i("EM", "EM---MessageActivity------>好友请求被拒绝");
        }

        @Override
        public void onContactInvited(String username, String reason) {
            //收到好友邀请
            Log.i("EM", "EM---MessageActivity------>收到好友邀请");
            Log.i("EM", "EM---MessageActivity------>username" + username + "\nreason" + reason);
            agreeAddUser(username, reason);
        }

        @Override
        public void onContactDeleted(String username) {
            //被删除时回调此方法
            Log.i("EM", "EM---MessageActivity------>被删除时回调此方法");
        }


        @Override
        public void onContactAdded(String username) {
            //增加了联系人时回调此方法
            Log.i("EM", "EM---MessageActivity------>增加了联系人时回调此方法");
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().chatManager().removeMessageListener(msgListener);
    }
}
